package com.controller;

import com.bean.BookReview;
import com.common.Result;
import com.service.BookReviewService;
import com.utils.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/book-reviews")
public class BookReviewController {
    @Autowired
    private BookReviewService bookReviewService;

    @GetMapping("/{reviewId}")
    public Result<BookReview> getBookReviewById(@PathVariable Integer reviewId) {
        BookReview bookReview = bookReviewService.getBookReviewById(reviewId);
        if (bookReview != null) {
            return Result.success(bookReview);
        } else {
            return Result.fail("书籍评价不存在");
        }
    }

    @GetMapping("/book/{bookId}")
    public Result<PageInfo<BookReview>> getReviewsByBookIdWithKeyword(@PathVariable Integer bookId,
                                                                      @RequestParam(required = false) String keyword,
                                                                      @RequestParam(defaultValue = "1") int pageNum,
                                                                      @RequestParam(defaultValue = "10") int pageSize) {
        PageInfo<BookReview> pageInfo = bookReviewService.getReviewsByBookIdWithKeyword(bookId, keyword, pageNum, pageSize);
        return Result.success(pageInfo);
    }

    @PostMapping
    public Result<Boolean> insertBookReview(@RequestBody BookReview bookReview) {
        boolean result = bookReviewService.insertBookReview(bookReview);
        if (result) {
            return Result.success(true);
        } else {
            return Result.fail("插入书籍评价失败");
        }
    }

    @PutMapping
    public Result<Boolean> updateBookReview(@RequestBody BookReview bookReview) {
        boolean result = bookReviewService.updateBookReview(bookReview);
        if (result) {
            return Result.success(true);
        } else {
            return Result.fail("更新书籍评价失败，评价可能不存在");
        }
    }

    @DeleteMapping("/{reviewId}")
    public Result<Boolean> deleteBookReviewById(@PathVariable Integer reviewId) {
        boolean result = bookReviewService.deleteBookReviewById(reviewId);
        if (result) {
            return Result.success(true);
        } else {
            return Result.fail("删除书籍评价失败，评价可能不存在");
        }
    }
}